package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.${capitalize};
import cn.wolfcode.wolf2w.query.${capitalize}QueryObject;
import cn.wolfcode.wolf2w.repository.${capitalize}Repository;
import cn.wolfcode.wolf2w.service.I${capitalize}Service;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ${capitalize}ServiceImpl implements I${capitalize}Service {

    @Autowired
    private ${capitalize}Repository ${uncapitalize}Repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(${capitalize} ${uncapitalize}) {
        ${uncapitalize}.setId(null);
        ${uncapitalize}Repository.save(${uncapitalize});
    }

    @Override
    public void delete(String id) {
        ${uncapitalize}Repository.deleteById(id);
    }

    @Override
    public void update(${capitalize} ${uncapitalize}) {
        ${uncapitalize}Repository.save(${uncapitalize});
    }

    @Override
    public ${capitalize} get(String id) {
        return ${uncapitalize}Repository.findById(id).orElse(null);
    }

    @Override
    public List<${capitalize}> list() {
        return ${uncapitalize}Repository.findAll();
    }

    @Override
    public Page<${capitalize}> query(${capitalize}QueryObject qo) {
        // 创建拼接对象
        Query query = new Query();
        // 使用PageRequest.of,传入当前页 - 1 (记得-1, 因为当前页从0开始), 页面显示条数, 排序规则, 排序的列
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, qo, query, pageable, ${capitalize}.class);
    }


}
